import gtk
from misc.misc import interpolate
from gobject import timeout_add

from gui.helperFuncs import *
from chartGen import genCharts

import dpcDBs as dbs
from dpcDBs.log import log
from gui.charting import chart, histChart


def genLabel( s ):
  l = gtk.Label( s )
  l.show()
  return l

class challengeSummary( gtk.Table ):
  def getChallengeID( self ):
    return self.challengeID

  def getScores( self ):
    return self.inter.getScores()

  def reset( self, user, newID ):
    log.i( self, 'Resetting challenge details (' + str( newID ) + ')' )
    self.user = user
    self.challengeID = newID
    self.initialised = False
    self.refresh()



  def copy( self, button ):
    log.i( self, 'Copying challenge information to clipboard (ID=' + str( self.challengeID ) + ')' )
    ch = dbs.challengeTable.selectBy( user = self.user, challengeID = self.challengeID ).getOne()
    scores = dbs.voteTable.selectBy( challenge = ch )
    if scores.count() == 0:
      print "No scores to copy"
      return

    # Generate the summary of everything
    score = scores[-1]
    colIDs = dbs.voteTable.getColumns()
    colNames = dbs.voteTable.getColumns( True )

    s = ch.challengeName + " scores...\n"
    for i in zip( colIDs, colNames ):
      s += i[1] + ': ' + str( score[i[0]] ) + "\n"
    s += "\n\n"



    # Generate the line chart
    l, h = genCharts( self.scores, self.hist )
    clip = gtk.Clipboard()
    clip.set_text( l + "\n" + h )





  def export( self, button ):
    log.i( self, 'Exporting challenge information to file' )

    ch = dbs.challengeTable.selectBy( user = self.user, challengeID = self.challengeID ).getOne()
    scores = dbs.voteTable.selectBy( challenge = ch )
    if scores.count() == 0:
      print "No scores to export"
      return


    colIDs = dbs.voteTable.getColumns()
    colNames = dbs.voteTable.getColumns( True )

    # Generate the header
    l = ''
    for c in colNames:
      l += c + ','
    print l

    # And generate the rows of data
    for s in scores:
      l = ''
      for c in colIDs:
        l += str( s[c] ) + ','
      print l



  def refresh( self ):
    #print "Refreshing"
    if self.user == None or self.challengeID == None:
      pass
    log.i( self, 'Refreshing challenge table from DB' )

    if not self.initilised:
      self.histPlot = histChart()
      self.linePlot = chart()

      # Set size and attach
      self.resize( 2, 2 )
      self.attach( self.vbox, 0, 1, 0, 1, gtk.EXPAND | gtk.FILL, gtk.FILL, 10, 10 )
      self.attach( self.histPlot, 1, 2, 0, 1, gtk.EXPAND | gtk.FILL, gtk.FILL )
      self.attach( self.linePlot, 0, 2, 1, 2, gtk.EXPAND | gtk.FILL, gtk.EXPAND | gtk.FILL )
      self.set_row_spacings( 10 )
      self.set_col_spacings( 10 )

      self.initilised = True


    # Generate the charts
    self.inter = interpolate( self.user, self.challengeID )

    # Set line/bar plot data
    self.hist = self.inter.getHist()
    self.scores = self.inter.getScores()
    last = self.scores[-1]


    self.histPlot.set_data( [[i + 1, v] for i, v in enumerate( self.hist )], 'Score histogram' )
    self.linePlot.appendData( 'Score trend', [ [ v.vote  for v in self.scores],
                                               [ v.score for v in self.scores] ] )

    self.histPlot.show()
    self.linePlot.show()

    # Generate the summary
    self.votesLabel.set_text( "Votes: %d" % last.votes )
    self.viewsLabel.set_text( "Views: %d" % last.views )
    self.scoreLabel.set_text( "Score: %.4f" % last.score )
    self.commentsLabel.set_text( "Comments: %d" % last.comments )
    self.favouritesLabel.set_text( "Favourites: %d" % last.favourites )
    self.wishlistsLabel.set_text( "Wish list: %d" % last.wishList )




    # Show everything
    self.histPlot.show()
    self.linePlot.show()
    self.vbox.show()
    self.show()

    return True



  def cleanup( self ):
    self.keepRepeating = False


  def __init__( self, user = None, challengeID = None ):
    gtk.Table.__init__( self )
    self.user = user
    self.challengeID = challengeID

    self.set_size_request( 400, 500 )

    self.set_border_width( 10 )
    self.set_row_spacings( 10 )
    self.set_col_spacings( 10 )



    # Attach to the table

    expand = False
    fill = True
    padding = 10

    # Initialise the labels
    self.votesLabel = genLabel( "Votes: " )
    self.viewsLabel = genLabel( "Views: " )
    self.scoreLabel = genLabel( "Score: " )
    self.commentsLabel = genLabel( "Comments: " )
    self.favouritesLabel = genLabel( "Favourites: " )
    self.wishlistsLabel = genLabel( "Wish list: " )


    # Copy and export buttons
    box = gtk.HBox()
    b = imageButton_stock( text = "Copy scores", label = "Copy",
                           stockID = gtk.STOCK_COPY,
                           size = gtk.ICON_SIZE_SMALL_TOOLBAR )
    b.connect( 'clicked', self.copy )
    b.show()
    box.pack_start( b, gtk.EXPAND | gtk.FILL, gtk.SHRINK, padding )

    b = imageButton_stock( text = "Export scores", label = "Export",
                           stockID = gtk.STOCK_QUIT,
                           size = gtk.ICON_SIZE_SMALL_TOOLBAR )
    b.connect( 'clicked', self.export )
    b.show()
    box.pack_start( b, gtk.EXPAND | gtk.FILL, gtk.SHRINK, padding )

    box.show()

    #
    self.vbox = gtk.VBox()
    self.vbox.pack_start( box, expand, fill, padding )
    self.vbox.pack_start( self.votesLabel, expand, fill, padding )
    self.vbox.pack_start( self.viewsLabel, expand, fill, padding )
    self.vbox.pack_start( self.scoreLabel, expand, fill, padding )
    self.vbox.pack_start( self.commentsLabel, expand, fill, padding )
    self.vbox.pack_start( self.favouritesLabel, expand, fill, padding )
    self.vbox.pack_start( self.wishlistsLabel, expand, fill, padding )
    self.vbox.show()

    self.initilised = False
    #timeout_add( 1000, self.refresh )


def main():
  def callback( s ):
    pass

  dbs.validateDBs()
  ch = challengeSummary( 1548 )
  ch.refresh()

  window = gtk.Window()

  window.set_title( "DPC Challenge Monitor" )
  window.set_size_request( 400, 500 )
  window.connect( "destroy", gtk.main_quit )
  window.add( ch )
  window.show_all()

  gtk.main()

  return 0

if __name__ == "__main__":
  main()
